//
//  udpManger.m
//  udp
//
//  Created by 崔 on 16/9/11.
//  Copyright © 2016年 崔. All rights reserved.
//

#import "udpManger.h"
#import <GCDAsyncUdpSocket.h>

#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <unistd.h>
#import "LGController.h"


@interface udpManger () <GCDAsyncUdpSocketDelegate>
/**udp*/
@property (nonatomic ,strong) GCDAsyncUdpSocket *udpSocket;


/**记录字符串*/
@property (nonatomic ,strong) NSString *recordStr;
@end

@implementation udpManger

- (void)openUDPServer:(NSString *)ip port:(UInt16)port{
    
    self.udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)];

    NSError *error;
    
    [_udpSocket bindToPort:port error:&error];
    
    if (nil != error) {
        
        NSLog(@"failed.:%@",[error description]);
        
    }
    
    [_udpSocket enableBroadcast:YES error:&error];
    
    if (nil != error) {
        
        NSLog(@"failed.:%@",[error description]);
        
    }
    
    //组播224.0.0.2地址，如果地址大于224的话，就要设置GCDAsyncUdpSocket的TTL （默认TTL为1）
    
    [_udpSocket joinMulticastGroup:ip error:&error];
    
    if (nil != error) {
        
        NSLog(@"failed.:%@",[error description]);
        
    }
    
    [_udpSocket beginReceiving:&error];
    
    if (nil != error) {
        
        NSLog(@"failed.:%@",[error description]);
        
    }
    
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
      fromAddress:(NSData *)address
withFilterContext:(nullable id)filterContext{
    
    LGController *controller = [[LGController alloc]initWithData:data];
    
    //通过一个KEY把controller存为字典,送出去
    NSDictionary *userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:controller,ALSSearchControllerNotificationUserInfoKey, nil];
    
    if (controller) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:ALSSearchControllerNotification object:self userInfo:userInfo];
    }
    
    
}

-(void)close{
//    NSLog(@"取消任务了");
    
    [self.udpSocket close];
    
}

@end

NSNotificationName const ALSSearchControllerNotification = @"ALSSearchControllerNotification";

NSString *const ALSSearchControllerNotificationUserInfoKey = @"ALSSearchControllerNotificationUserInfoKey";
